package com.harleyquinn.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: feign拦截器功能
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2024-01-04 21:10
 **/

@Configuration
public class FeignClientConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            //RequestTemplate为远程调用时构造的新的Request
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1、使用RequestContextHolder拿到远程调用之前的 ServletRequestAttributes
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes != null) {
                    //得到之前的Request
                    HttpServletRequest request = requestAttributes.getRequest();
                    if (request != null) {
                        //2、同步请求头的数据（主要是cookie），把之前请求的cookie值Set到新请求，进行一个同步
                        String cookie = request.getHeader("Cookie");
                        requestTemplate.header("Cookie", cookie);
                    }
                }
            }
        };
        return requestInterceptor;
    }
}
